﻿#region Using

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;

using Common.Enums;

using GameCommon.Base;
using GameCommon.FontHelper;
using GameCommon.ManagerInterfaces;
using GameCommon.Services;

using Microsoft.Xna.Framework;

#endregion

namespace GameCommon.Manager
{
    internal class FontManager : IFontManager
    {
        private readonly Dictionary<string, Font> fonts;

        public FontManager()
        {
            this.fonts = new Dictionary<string, Font>();
            this.LoadAllFonts();
        }

        public Font GetFont(FontEnum fontEnum, FontSizeEnum size)
        {
            Font font;
            if (this.fonts.TryGetValue(Service.PathService.GetFontName(fontEnum, size), out font))
            {
                return font;
            }

            return null;
        }

        private static FontFile Load(Stream stream)
        {
            var deserializer = new XmlSerializer(typeof(FontFile));
            var file = (FontFile)deserializer.Deserialize(stream);
            return file;
        }

        private void LoadAllFonts()
        {
            var fontList = Enum.GetValues(typeof(FontEnum)).Cast<FontEnum>().ToList();
            var sizeList = Enum.GetValues(typeof(FontSizeEnum)).Cast<FontSizeEnum>().ToList();

            foreach (var font in fontList)
            {
                sizeList.ForEach(size => this.LoadFont(font, size));
            }
        }

        private void LoadFont(FontEnum fontEnum, FontSizeEnum size)
        {
            string path;
            try
            {
                path = Service.PathService.GetFontFile(fontEnum, size);
            }
            catch (Exception)
            {
                return;
            }

            using (var stream = TitleContainer.OpenStream(path))
            {
                var font = new Font();
                font.File = Load(stream);
                font.Texture = Managers.ContentManager.GetFontTexture2D(fontEnum, size);

                this.fonts.Add(Service.PathService.GetFontName(fontEnum, size), font);
            }
        }
    }
}